﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.ComponentModel;
using DataTurnClient.Enum;
using System.Windows.Interop;


namespace DataTurnClient.Server
{
    /// <summary>
    /// http请求类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Post<T>
    {
        /// <summary>
        /// 接口地址，Api的接口地址
        /// </summary>
        public string Post_url;//接口地址
        /// <summary>
        /// 请求类型,（Get/Post）
        /// </summary>
        public DType.RequestType Post_mode;//请求类型
        /// <summary>
        /// 如果是post请求，需选择x-www-form与json格式，如果没有定义默认是json
        /// </summary>
        public bool Post_format;//post请求格式
        /// <summary>
        /// 如果需要在请求头加Cookie，则传入时加入，无传则不加
        /// </summary>
        public string Post_Cookie;//请求头加Cookie
        /// <summary>
        /// 请求数据
        /// </summary>
        public T Post_data;//请求数据

        /// <summary>
        /// 发送请求
        /// </summary>
        /// <returns></returns>
        public Result<T> PostSend()
        {
            Result<T> result = new Result<T>();
            result.Code = 200;
            result.Message = "成功";
            result.Success = true;
            if (Post_url == "")
            {
                result.Code = 500;
                result.Message = "url参数不能为空";
                result.Success = false;
                return result;
            }
            else
            {
                if (Post_mode == DType.RequestType.Post)
                {
                    return Post_Mode_post(Post_url, Post_data, Post_Cookie, Post_format);
                }
                if (Post_mode == DType.RequestType.Get)
                {
                    return Post_Mode_get(Post_url);
                }
            };
            return result;
        }
        private Result<T> Post_Mode_post(string Post_url, T Post_data, string Post_Cookie, bool Post_format)
        {
            Result<T> result = new Result<T>();
            result.Code = 200;
            result.Message = "成功";
            result.Success = true;
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(Post_url);
                if (Post_format == false)
                {
                    httpWebRequest.ContentType = "application/json";
                }
                else
                {
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                }
                httpWebRequest.Method = WebRequestMethods.Http.Post;
                if (Post_Cookie != null)
                {
                    httpWebRequest.Headers.Add("Cookie", Post_Cookie);
                }
                using (Stream reqStream = httpWebRequest.GetRequestStream())
                {
                    UTF8Encoding encoding = new UTF8Encoding();
                    System.Diagnostics.Debug.WriteLine($"{JsonConvert.SerializeObject(Post_data)}");
                    byte[] bytes = encoding.GetBytes($"{JsonConvert.SerializeObject(Post_data)}");
                    reqStream.Write(bytes, 0, bytes.Length);
                }
                using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {
                    var responseStream = httpWebResponse.GetResponseStream();
                    result.Data = JsonConvert.DeserializeObject<T>(responseStream == null ? null : new StreamReader(responseStream, Encoding.UTF8).ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = $"请求{Post_url}时遇到错误：{ex.Message}";
                result.Success = false;
            }
            return result;
        }
        private Result<T> Post_Mode_get(string Post_url)
        {
            Result<T> result = new Result<T>();
            result.Code = 200;
            result.Message = "成功";
            result.Success = true;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Post_url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                result.Data = JsonConvert.DeserializeObject<T>(retString);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = $"请求{Post_url}时遇到错误：{ex.Message}";
                result.Success = false;
            }
            return result;
        }
        /// <summary>
        /// 如果是x-www-form请求。使用此方法拼接参数Url
        /// </summary>
        /// <param name="source">要拼接的实体类</param>
        public string ToPaeameter(object source)
        {
            var buff = new StringBuilder(string.Empty);
            if (source == null)
                throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
            {
                object value = property.GetValue(source);
                if (value != null)
                {
                    buff.Append(WebUtility.UrlEncode(property.Name) + "=" + WebUtility.UrlEncode(value + "") + "&");
                }
            }
            return buff.ToString().Trim('&');
        }
        public string Return(string msg)
        {
            return msg;
        }
    }
}
